/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Image,
    ListView,
    Platform,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableHighlight,
    View
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ModalListUtils from "../../../utils/ModalListUtils";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from '../../../res/language/i18n'
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import IparInput from "../../../custom/IparInput";


const checkedImage = require('../../../res/images/ic_check_box.png');
const checkImage = require('../../../res/images/ic_check_box_outline_blank.png');
let countryData = [];
let provinceData = [];
let cityData = [];
let districtData = [];
export default class AddAddressPage extends Component {
    constructor(props) {
        super(props);
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        countryData = [];
        provinceData = [];
        cityData = [];
        districtData = [];
        this.state = {
            countrySource: ds,
            provinceSource: ds,
            citySource: ds,
            districtSource: ds,
            showLoading: true,
            modalDialog: false,
            isDateTimePickerVisible: false,
            selectCountry: '',
            selectProvince: '',
            selectCity: '',
            selectDistrictCity: '',
            interPostBox: '',
            modalDataType: 'country',
            streetNumber: '',
            buildingName: '',
            goodsUserName: '',
            goodsUserMobile: '',
            //statusCode: undefined,
            //cityCode: undefined,
            postcode: '',
            countryId: '',
            userId: '',
            defaultAddress: 'Default',
            isChecked: this.props.isChecked || true,
            cityType: false,
            districtType: false,
        };

        this.iparNetwork = new IparNetwork()
    }


    componentWillUnmount() {
        this.iparNetwork = null;

    }

    componentDidMount() {


        /*获取本地数据*/
        CommonUtils.getAcyncInfo('userInfo').then((result) => {
            let resultData = JSON.parse(result);
            this.setState({
                userId: resultData.main_user_id,
            });

            this.getAddressInfo();
        });

    }

    /*获取用户收货地址信息姐*/
    getAddressInfo() {
        countryData = [];
        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?',)//'lang=' + lang
            .then((result) => {
                for (i = 0; i < result.length; i++) {
                    countryData.push(result[i]);
                }
                this.setState({
                    showLoading: false,
                    countrySource: this.state.countrySource.cloneWithRows(result)
                });

            })
            .catch((error) => {
                this.setState({showLoading: false});
                console.log(error);
            })
    }


    /*获取用户收货地址信息姐*/
    getProvinceInfo(level, selectCountry) {


        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?', 'level=' + level + '&parent=' + selectCountry)
            .then((result) => {
                this.setState({
                    showLoading: false,
                });

                if (level === 1) {
                    provinceData = [];
                    for (i = 0; i < result.length; i++) {
                        provinceData.push(result[i])
                    }
                    this.setState({
                        provinceSource: this.state.provinceSource.cloneWithRows(result)
                    });


                } else if (level === 2) {
                    cityData = [];
                    for (i = 0; i < result.length; i++) {
                        cityData.push(result[i])
                    }
                    if (result.length > 0) {
                        this.setState({
                            citySource: this.state.citySource.cloneWithRows(result),
                            cityType: true,
                        });
                    } else {
                        this.setState({cityType: false,});//cityCode: 'code'
                    }
                } else {
                    districtData = [];
                    for (i = 0; i < result.length; i++) {
                        districtData.push(result[i])
                    }
                    if (result.length > 0) {
                        this.setState({
                            districtSource: this.state.districtSource.cloneWithRows(result),
                            districtType: true
                        });
                    } else {
                        this.setState({
                            districtType: false
                        });
                    }

                }

            })
            .catch((error) => {
                this.setState({showLoading: false});
                console.log(error)
            })
    }


    /*用户地址btn 点击*/
    editAddress() {
        if (this.state.selectCountry === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectCountry'))
        } else if (this.state.selectProvince === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectProvince'))
        } else if (this.state.selectCity === '' && this.state.cityType == true) {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectCity'))
        } else if (this.state.selectDistrictCity === '' && this.state.districtType == true) {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectDistrict'))
        } else if (this.state.streetNumber.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.streetNumber'))
        } else if (this.state.buildingName.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.buildingName'))
        } else if (this.state.postcode.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.postNumber'))
        } else if (this.state.goodsUserName.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.goodsUserName'))
        } else if (this.state.goodsUserMobile.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.goodsUserMobile'))
        } else {
            this.getAddress();
        }

    }

    /**
     * 添加收货地址
     * */
    getAddress() {

        CommonUtils.showLoading();

        let formData = new FormData();
        formData.append("userId", this.state.userId);
        formData.append("addressId", this.state.countryId);
        formData.append("defaultAddress", this.getChecked() === false ? 0 : 1);
        formData.append("streetName", this.state.streetNumber);
        formData.append("building", this.state.buildingName);
        formData.append("postCode", this.state.postcode);
        formData.append("userName", this.state.goodsUserName);
        formData.append("mobile", this.state.goodsUserMobile);


        this.iparNetwork.getPostFrom(SERVER_TYPE.logistics + 'useraddress/add', formData)
            .then((result) => {
                if (result.code === 200) {
                    this.props.callback('full');
                    this.props.navigator.pop();
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })
    }

    /*dialog item 点击*/
    itemClickListener(index, text) {

        switch (this.state.modalDataType) {
            case 'country':
                this.getProvinceInfo(1, countryData[index].name);
                this.setState({
                    selectCountry: text,
                    modalDialog: false,
                    postcode: countryData[index].postcode ? countryData[index].postcode : '',
                    countryId: countryData[index].id,
                    cityType: false,
                    districtType: false,
                    selectProvince: '',
                    selectCity: '',
                    selectDistrictCity: '',
                });
                break;
            case 'region1':
                this.getProvinceInfo(2, provinceData[index].name);
                this.setState({
                    selectProvince: text,
                    modalDialog: false,
                    postcode: provinceData[index].postcode ? provinceData[index].postcode : '',
                    countryId: provinceData[index].id,
                    cityType: false,
                    districtType: false,
                    selectCity: '',
                    selectDistrictCity: '',
                });
                break;
            case 'region2':
                this.getProvinceInfo(3, cityData[index].name);
                this.setState({
                    selectCity: text,
                    modalDialog: false,
                    postcode: cityData[index].postcode ? cityData[index].postcode : '',
                    countryId: cityData[index].id,
                    districtType: false,
                    selectDistrictCity: '',
                });
                break;
            case 'region3':
                // this.getProvinceInfo(4, districtData[index].name);
                this.setState({
                    selectDistrictCity: text,
                    modalDialog: false,
                    postcode: districtData[index].postcode ? districtData[index].postcode : '',
                    countryId: districtData[index].id,
                });
                break;


        }


    }

    /*showDialog*/
    showDialog(type) {
        switch (type) {
            case 0:
                this.setState({
                    modalDialog: true,
                    modalDataType: 'country'
                });
                break;
            case 1:
                this.setState({
                    modalDialog: true,
                    modalDataType: 'region1'
                });
                break;
            case 2:
                this.setState({
                    modalDialog: true,
                    modalDataType: 'region2'
                });
                break;
            case 3:
                this.setState({
                    modalDialog: true,
                    modalDataType: 'region3'
                });
                break;


        }


    }

    /*获取 checkbox true false*/
    getChecked() {
        return this.state.isChecked;
    }

    /*isChecked*/
    checkClick() {
        this.setState({
            isChecked: !this.state.isChecked
        });
    }


    render() {

        /*dialog dataSource*/
        let _dataSource = this.state.countrySource;
        switch (this.state.modalDataType) {
            case 'region1':
                _dataSource = this.state.provinceSource;
                break;
            case 'region2':
                _dataSource = this.state.citySource;
                break;
            case 'region3':
                _dataSource = this.state.districtSource;
                break;

        }


        return (


            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    onClickLeftBtn={() => {
                        // this.props.callback('sfsdf');
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}

                />
                <ModalListUtils
                    close={() => {
                        this.setState({
                            modalDialog: false
                        })
                    }}
                    onPress={(index, text) => this.itemClickListener(index, text)}
                    visible={this.state.modalDialog}
                    dataSource={_dataSource}
                    dataParam={this.state.modalDataType}
                />

                <KeyboardAwareScrollView

                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.showLoading}
                            onRefresh={() => {
                            }}
                        />
                    }

                    style={StyleUtils.flex}>
                    <View style={{padding: 16}}>
                        {ViewUtils.getTitleView('Add address', 'Add address your account information')}

                        {ViewUtils.getButtunMenu(this.state.selectCountry ? this.state.selectCountry : I18n.t('default.selectCountry'), () => this.showDialog(0))}
                        {ViewUtils.getButtunMenu(this.state.selectProvince ? this.state.selectProvince : I18n.t('default.selectProvince'), () => this.showDialog(1), {marginTop: 16})}

                        {this.state.cityType ? ViewUtils.getButtunMenu(this.state.selectCity ? this.state.selectCity : I18n.t('default.selectCity'), () => this.showDialog(2), {marginTop: 16}) : false}


                        {this.state.districtType ? ViewUtils.getButtunMenu(this.state.selectDistrictCity ? this.state.selectDistrictCity : I18n.t('default.selectDistrict'), () => this.showDialog(3), {marginTop: 16}) : false}

                        <Text style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.streetNumber')}</Text>


                        <IparInput
                            onChangeText={(value) => {
                                this.setState({streetNumber: value})
                            }}
                            placeholder={this.state.streetNumber ? this.state.streetNumber : I18n.t('default.streetNumber')}/>


                        <Text style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.buildingName')}</Text>


                        <IparInput
                            onChangeText={(value) => {
                                this.setState({buildingName: value})
                            }}
                            placeholder={this.state.buildingName ? this.state.buildingName : I18n.t('default.buildingName')}/>


                        <Text style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.postalCode')}</Text>

                        <IparInput
                            onChangeText={(value) => {
                                this.setState({postcode: value})
                            }}
                            placeholder={this.state.postcode ? this.state.postcode : I18n.t('default.postalCode')}/>


                        <IparInput
                            onChangeText={(value) => {
                                this.setState({goodsUserName: value})
                            }}
                            placeholder={I18n.t('default.goodsUserName')}/>


                        <IparInput
                            onChangeText={(value) => {
                                this.setState({goodsUserMobile: value})
                            }}
                            keyboardType={'number-pad'}
                            placeholder={I18n.t('default.goodsUserMobile')}/>


                        <View style={[StyleUtils.rowDirection, StyleUtils.smallFont, {alignItems: 'center'}]}>
                            <TouchableHighlight underlayColor={'transparent'} onPress={() => this.checkClick()}>
                                <Image source={this.state.isChecked ? checkedImage : checkImage}
                                       style={styles.checkImage}/>
                            </TouchableHighlight>
                            <Text
                                style={[styles.checkBoxTv, StyleUtils.smallFont]}>{this.state.isChecked ? I18n.t('default.defaultTv') : I18n.t('default.setDefault')}</Text>
                        </View>
                        {ViewUtils.getButton(I18n.t('default.submit'), () => {
                            this.editAddress()
                        }, {marginTop: 50})}
                    </View>

                </KeyboardAwareScrollView>
            </View>
        );
    }


}

const styles = StyleSheet.create({
    defaultTv: {
        marginTop: 16,
        textAlign: 'left'

    },
    checkImage: {
        marginTop: 16,
        height: 20,
        width: 20
    },
    checkBoxTv: {
        marginTop: 12,
        color: 'black',
        marginLeft: 8
    }
});
